package com.yumi.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yumi.entity.PerformanceAppraisal;
import com.yumi.mapper.PerformanceAppraisalMapper;
import com.yumi.service.PerformanceAppraisalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 绩效考核服务实现类
 */
@Service
@Slf4j
public class PerformanceAppraisalServiceImpl extends ServiceImpl<PerformanceAppraisalMapper, PerformanceAppraisal> implements PerformanceAppraisalService {

    /**
     * 新增考核记录
     * @param performanceAppraisal 考核记录信息
     * @return 是否添加成功
     */
    @Override
    public boolean addPerformanceAppraisal(PerformanceAppraisal performanceAppraisal) {
        log.info("新增考核记录：{}", performanceAppraisal);
        return save(performanceAppraisal);
    }

    /**
     * 修改考核记录
     * @param performanceAppraisal 考核记录信息
     * @return 是否修改成功
     */
    @Override
    public boolean updatePerformanceAppraisal(PerformanceAppraisal performanceAppraisal) {
        log.info("修改考核记录：{}", performanceAppraisal);
        return updateById(performanceAppraisal);
    }

    /**
     * 删除考核记录
     * @param id 考核ID
     * @return 是否删除成功
     */
    @Override
    public boolean deletePerformanceAppraisal(Long id) {
        log.info("删除考核记录，ID：{}", id);
        return removeById(id);
    }

    /**
     * 根据ID查询考核详情
     * @param id 考核ID
     * @return 考核记录信息
     */
    @Override
    public PerformanceAppraisal getPerformanceAppraisalById(Long id) {
        return getById(id);
    }

    /**
     * 分页查询考核记录
     * @param page 分页信息
     * @param employeeId 员工ID
     * @param grade 考核等级
     * @return 考核记录分页结果
     */
    @Override
    public Page<PerformanceAppraisal> getPerformanceAppraisalPage(Page<PerformanceAppraisal> page, Long employeeId, String grade) {
        LambdaQueryWrapper<PerformanceAppraisal> queryWrapper = new LambdaQueryWrapper<>();
        
        // 根据条件构建查询
        if (employeeId != null) {
            queryWrapper.eq(PerformanceAppraisal::getEmployeeId, employeeId);
        }
        
        if (StringUtils.hasText(grade)) {
            queryWrapper.eq(PerformanceAppraisal::getGrade, grade);
        }
        
        // 按考核周期降序排序
        queryWrapper.orderByDesc(PerformanceAppraisal::getPeriodEnd);
        
        return page(page, queryWrapper);
    }

    /**
     * 获取员工考核历史记录
     * @param employeeId 员工ID
     * @return 员工考核历史列表
     */
    @Override
    public List<PerformanceAppraisal> getEmployeePerformanceHistory(Long employeeId) {
        LambdaQueryWrapper<PerformanceAppraisal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PerformanceAppraisal::getEmployeeId, employeeId)
                .orderByDesc(PerformanceAppraisal::getPeriodEnd);
        
        return list(queryWrapper);
    }

    /**
     * 导出绩效考核数据到Excel
     * @param employeeId 员工ID
     * @param grade 考核等级
     * @param response HTTP响应对象
     * @throws IOException IO异常
     */
    @Override
    public void exportToExcel(Long employeeId, String grade, HttpServletResponse response) throws IOException {
        log.info("开始导出绩效考核数据，员工ID：{}，考核等级：{}", employeeId, grade);
        
        // 查询符合条件的数据
        LambdaQueryWrapper<PerformanceAppraisal> queryWrapper = new LambdaQueryWrapper<>();
        if (employeeId != null) {
            queryWrapper.eq(PerformanceAppraisal::getEmployeeId, employeeId);
        }
        if (StringUtils.hasText(grade)) {
            queryWrapper.eq(PerformanceAppraisal::getGrade, grade);
        }
        queryWrapper.orderByDesc(PerformanceAppraisal::getPeriodEnd);
        
        List<PerformanceAppraisal> dataList = list(queryWrapper);
        log.info("查询到{}条数据", dataList.size());
        
        // 创建工作簿和工作表
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("绩效考核数据");
            
            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {
                    "考核ID", "员工ID", "考核开始日期", "考核结束日期", 
                    "考核内容", "考核指标", "考核得分", "考核等级", 
                    "考核评语", "评价人ID", "创建时间"
            };
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.autoSizeColumn(i);
            }
            
            // 填充数据行
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            
            int rowNum = 1;
            for (PerformanceAppraisal data : dataList) {
                Row row = sheet.createRow(rowNum++);
                
                row.createCell(0).setCellValue(data.getId() != null ? data.getId() : 0);
                row.createCell(1).setCellValue(data.getEmployeeId() != null ? data.getEmployeeId() : 0);
                row.createCell(2).setCellValue(data.getPeriodStart() != null ? data.getPeriodStart().format(dateFormatter) : "");
                row.createCell(3).setCellValue(data.getPeriodEnd() != null ? data.getPeriodEnd().format(dateFormatter) : "");
                row.createCell(4).setCellValue(data.getContent() != null ? data.getContent() : "");
                row.createCell(5).setCellValue(data.getIndicators() != null ? data.getIndicators() : "");
                row.createCell(6).setCellValue(data.getScore() != null ? data.getScore().doubleValue() : 0);
                row.createCell(7).setCellValue(data.getGrade() != null ? data.getGrade() : "");
                row.createCell(8).setCellValue(data.getComment() != null ? data.getComment() : "");
                row.createCell(9).setCellValue(data.getEvaluatorId() != null ? data.getEvaluatorId() : 0);
                row.createCell(10).setCellValue(data.getCreateTime() != null ? data.getCreateTime().format(datetimeFormatter) : "");
            }
            
            // 调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 设置响应头
            String filename = "绩效考核数据_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()));
            
            // 写入响应输出流
            workbook.write(response.getOutputStream());
            log.info("绩效考核数据导出成功");
        } catch (Exception e) {
            log.error("导出Excel时发生错误", e);
            throw e;
        }
    }
} 